package com.sikao.app.net;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import com.sikao.app.R;
import com.sikao.app.app.MyApplication;
import com.sikao.app.bean.Bean;
import com.sikao.app.bean.UpdateApkBean;
import com.sikao.app.dao.CheckAppUpdateModel;
import com.sikao.app.utils.EquipmentUtils;
import com.sikao.app.utils.FileUtils;
import com.sikao.app.utils.SharepreferenceUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

public class UpdateApk {
	private Context mContext;

	private Dialog downloadDialog;

	private CheckAppUpdateModel checkAppUpdateModel;
	private FileDownloadCallback callback;
	//下载包安装路径
	private static final String savePath = FileUtils.tempPath;
	private static final String saveFileName ="bigmall.apk";
	// 进度条与通知ui刷新的handler和msg常量
	private ProgressBar mProgress;
	private int progress;
	private boolean isNotice;
	private String url;//软件url
	private SharepreferenceUtil sp;

	public UpdateApk(Context context, boolean isNotice) {
		this.mContext = context;
		this.isNotice = isNotice;
	}

	public void checkUpdateInfo(boolean isShow) {
		if (checkAppUpdateModel == null) {
			checkAppUpdateModel = new CheckAppUpdateModel(mContext, new OnNetBackListener<UpdateApkBean>() {
				@Override
				public void netBack(UpdateApkBean data) {
					if (data == null){
						return;
					}
					if (data.getStatus() == 1){
						if (EquipmentUtils.getVersionName().equals(data.getRes().getVersion()) && isNotice){
							Toast.makeText(mContext, "当前已是最新版本", Toast.LENGTH_SHORT).show();
						}
						if (!EquipmentUtils.getVersionName().equals(data.getRes().getVersion())){
							url = data.getRes().getUrl();
							showNoticeDialog();
						}
					}
				}
			});
		}
		checkAppUpdateModel.request("{\"type\":\"android\"}", isShow);

	}

	private String appVersion;
	private int versionCode;

	/**
	 * 获得版本号
	 */

	public int getVerCode(Context context) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo("com.zks.FoodSafety", 0).versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			Log.e("版本号获取异常", e.getMessage());
		}
//		Log.e("verCode",""+ verCode);
		PackageManager manager = mContext.getPackageManager();
		try {
			PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
			appVersion = info.versionName;   //版本名
			versionCode = info.versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			Toast.makeText(mContext, appVersion + "", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		Log.e("verCode", "" + verCode);
		return versionCode;
	}

	/**
	 * 获得版本名称
	 */
	public String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo("com.zhizi.zhizisq", 0).versionName;
		} catch (PackageManager.NameNotFoundException e) {
			Log.e("版本名称获取异常", e.getMessage());
		}
		return verName;
	}

	public void showNoticeDialog() {


		//    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		//    设置Title的图标
		//builder.setIcon(R.mipmap.fund_record);
		//    设置Title的内容
		//    设置Content来显示一个信息
		builder.setMessage("软件有新版本，是否更新？");
		builder.setCancelable(false);
		//    设置一个PositiveButton
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				showDownloadDialog();
			}
		});
		//    设置一个NegativeButton
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		//    显示出该对话框
		builder.show();


	}

	private void showDownloadDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle("正在更新...");
		builder.setCancelable(false);
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progressBar);
		builder.setView(v);
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				OkHttpHelper.getInstance().cancelRequest(callback);
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();
		downloadApk(url);
	}

	/**
	 * 下载apk
	 */
	private void downloadApk(String url) {
		if (callback == null){
			callback = new FileDownloadCallback() {
				@Override
				public void onFailure(Request request, Exception e) {
					Toast.makeText(mContext, "网络异常", Toast.LENGTH_SHORT).show();
					downloadDialog.dismiss();
				}

				@Override
				public void onSuccess(Object o) {
					installApk();
					downloadDialog.dismiss();
				}

				@Override
				public void onAllSize(long allLength) {
					mProgress.setMax((int) (allLength/1000));
				}

				@Override
				public void onUpdateProgress(long length) {
					mProgress.setProgress((int) (length/1000));
				}

				@Override
				public void onError(Response response, int code, Exception e) {
					downloadDialog.dismiss();
				}
			};
		}
		OkHttpHelper.getInstance().downloadFile(url, savePath, saveFileName, callback);
	}

	/**
	 * 安装apk
	 */
	private void installApk() {
		File apkfile = new File(savePath + saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setAction(android.content.Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		//清除引导页信息
		sp = SharepreferenceUtil.getInstance(MyApplication.getInstance());
		sp.putString("isFirst","");

		mContext.startActivity(i);

	}
}

